package org.bangumibuddy.utils;

import org.bangumibuddy.pojo.TorrentFile;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class TorrentFilter {

    public static List<TorrentFile> filter(List<TorrentFile> torrentFiles, List<String> include, List<String> exclude) {
        List<TorrentFile> filteredTorrentFiles = torrentFiles.stream()
                .filter(torrentFile -> {
                    boolean isExclude = exclude.isEmpty() ? false : exclude.stream().anyMatch(torrentFile.getTorrentName()::contains);
                    boolean isExcludeRegex= exclude.stream().anyMatch(regex->{
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(torrentFile.getTorrentName());

                        while (matcher.find()) {
                            return true;
                        }
                        return false;
                    });
                    return !(isExclude || isExcludeRegex);
                })
                .collect(Collectors.toList());
        filteredTorrentFiles= filteredTorrentFiles.stream().filter(torrentFile -> {
            boolean isInclude = include.isEmpty() ? true : include.stream().anyMatch(torrentFile.getTorrentName()::contains);
            boolean isIncludeRegex= include.stream().anyMatch(regex->{
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(torrentFile.getTorrentName());

                while (matcher.find()) {
                    return true;
                }
                return false;
            });
            return isInclude || isIncludeRegex;
        }).collect(Collectors.toList());

        return filteredTorrentFiles;
    }
}
